package com.voodoo.lib_mqtt;

import com.voodoo.lib_logcat.L;
import com.voodoo.lib_mqtt.listener.MqttTopicMessageListener;
import com.voodoo.lib_utils.DeviceUtils;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.MqttException;

/**
 * Author：voodoo
 * CreateTime：2021/07/15 015 下午 05:15
 * Description：Mqtt发布的消息处理
 */
public class MqttOperation {

    volatile static MqttOperation mqttOperation;

    public static MqttOperation getInstance() {
        if (mqttOperation == null) {
            synchronized (MqttOperation.class) {
                if (mqttOperation == null) {
                    mqttOperation = new MqttOperation();
                }
            }
        }
        return mqttOperation;
    }

    public MqttOperation() {

    }

    /**
     * 订阅各个主题screenshots
     *
     * @param mqttClient Android链接
     * @throws MqttException MqttException
     */
    public void subscribeToTopic(MqttAndroidClient mqttClient) throws MqttException {
        mqttClient.subscribe(MqttConstant.SUBSCR_ADVERTISEMENT, 2); // 广告下发
        mqttClient.subscribe(MqttConstant.SUBSCR_LANE_UPDATA, 2); // 货道更新
        mqttClient.subscribe(MqttConstant.SUBSCR_OUT_GOODS, 2); // 远程出货
        mqttClient.subscribe(MqttConstant.SUBSCR_CMD, 2); // 远程获取日志
        mqttClient.subscribe(MqttConstant.SUBSCR_TEMPERATURE_CONTROL, 2); // 温度控制
        mqttClient.subscribe(MqttConstant.SUBSCR_OUTADV, 2); // 售货机接收广告推送
        mqttClient.subscribe(MqttConstant.SUBSCR_LOCK, 2); // 售货机电控锁
        mqttClient.subscribe(MqttConstant.BINDSUSCCESS, 2); // 售货机接收绑定重启软件
        mqttClient.subscribe(MqttConstant.SERVICE_TEL, 2); // 售货机接收更新机主电话
        mqttClient.subscribe(MqttConstant.SLOTSET, 2); // 售货机接收 设置转动时间
        L.i("全部订阅成功");
    }

    /**
     * 处理接收到的消息
     *
     * @param topic   消息头
     * @param message Mqtt消息
     */
    public void processMsg(String topic, String message) {
        if (mqttTopicMessageListener != null) {
            L.i("Mqtt收到服务器消息", "主题名称：" + topic, "接收消息：" + message);
            mqttTopicMessageListener.processMsg(topic, message);
        }
    }

    public MqttTopicMessageListener mqttTopicMessageListener;

    public void setMqttTopicMessageListener(MqttTopicMessageListener mqttTopicMessageListener) {
        this.mqttTopicMessageListener = mqttTopicMessageListener;
    }
}
